//
// Created by v on 19-5-29.
//

#include "CameraCapture.h"

int CameraCapture::open(int index) {
    m_cap = new cv::VideoCapture(index);
    if (!m_cap) {
        return -1;
    }
    return 0;
}

int CameraCapture::close() {
    if (m_cap) {
        delete m_cap;
    }
    return 0;
}

bool CameraCapture::opened() {
    return m_cap->isOpened();
}

bool CameraCapture::getFrame(cv::Mat &img) {
    if (m_cap) {
        return m_cap->read(img);
    }
    return false;
}

bool CameraCapture::Mat2QImage(const cv::Mat &mat, QImage &imgout)
{
    // 8-bits unsigned, NO. OF CHANNELS=1
    if(mat.type()==CV_8UC1)
    {
        // Set the color table (used to translate colour indexes to qRgb values)
        QVector<QRgb> colorTable;
        for (int i=0; i<256; i++)
            colorTable.push_back(qRgb(i,i,i));
        // Copy input Mat
        const uchar *qImageBuffer = (const uchar*)mat.data;
        // Create QImage with same dimensions as input Mat
        QImage img(qImageBuffer, mat.cols, mat.rows, mat.step, QImage::Format_Indexed8);
        img.setColorTable(colorTable);
        imgout = img;
        return true;
    }
    // 8-bits unsigned, NO. OF CHANNELS=3
    if(mat.type()==CV_8UC3)
    {
        // Copy input Mat
        const uchar *qImageBuffer = (const uchar*)mat.data;
        // Create QImage with same dimensions as input Mat
        QImage img(qImageBuffer, mat.cols, mat.rows, mat.step, QImage::Format_RGB888);
        imgout = img.rgbSwapped();
        return true;
    }

    return false;
}

bool CameraCapture::getImage(QImage &img) {
    if (m_cap) {
        cv::Mat ximg;
        bool ret = m_cap->read(ximg);
        if (ret) {
            return Mat2QImage(ximg, img);
        }
    }
    return false;
}
